/**
 * Copyright (c) 2008 Andrew Rapp. All rights reserved.
 *
 *  Modified by anis.darwich
 *  
 */

package clubhouse.communication;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.rapplogic.xbee.RxTxSerialComm;



public abstract class SerialComm extends RxTxSerialComm {

	private final static Logger log = Logger.getLogger(SerialComm.class);
	
	private String lastResponse = null;	
	private StringBuffer strBuf = new StringBuffer();

	public final int TIMEOUT = 1000;
	
	public final String CR = "fe"; // end of line
	
	public SerialComm() {
		super();
	}

	protected abstract Object getLock();
	
	protected void handleSerialData() throws IOException {

		log.debug("handleSerialData(): thread [" + Thread.currentThread().getName() + "]");
		
		byte[] readBuffer = new byte[7];
		
		// read data
		while (this.getInputStream().available() > 0) {
			int numBytes = this.getInputStream().read(readBuffer);
			
			//log.debug("read " + numBytes + " bytes");
			
			for (int i = 0; i < numBytes; i++) {

				String ch = Integer.toString( ( readBuffer[i] & 0xff ) + 0x100, 16).substring( 1 );

				//log.debug("Received: " + ch + ";");
				
				if ((ch.compareTo(CR) < 0) || (ch.compareTo(CR) > 0)) {
					//log.debug(">>> Appending to strBuf different from " + CR);
					strBuf.append(ch);
				}
				// CR
				if ( ch.compareTo(CR) == 0) {
					synchronized(this.getLock()) {
						//log.debug(strBuf.toString());
						lastResponse = strBuf.toString();
						log.debug("handleSerialData(): going to wake up thread");
						// wake up wait thread
						//log.debug(lastResponse);
						this.getLock().notify();
					}
					strBuf = new StringBuffer();
				}
			}
		}
		log.debug("handleSerialData(): Exiting\n");
	}
	
	/**
	 * Sends Command in ASCII. -> to modify, send normal hex  
	 * 
	 * @param commandSequence
	 * @param type
	 * @throws IOException
	 */
	protected void sendCommand(byte[] commandSequence) throws IOException {
		String result = "";
		for (int i=0; i < commandSequence.length; i++) {
			result += Integer.toString( ( commandSequence[i] & 0xff ) + 0x100, 16).substring( 1 );
		}
		log.debug("sendCommand(): sending hex " + result);

		this.getOutputStream().write(commandSequence);
		this.getOutputStream().flush();		
	}
	
	public String getLastResponse() {
		return lastResponse;
	}
	
	public void resetLastResponse() {
		lastResponse = null;
	}

	public StringBuffer getStrBuf() {
		return strBuf;
	}
	
}
